package com.shi.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import com.shi.view.LoginJFrame;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileAppender;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

public class EncodeUtil {

	final static  String key = "1234567891234567";
	final static byte[] byteKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), key.getBytes()).getEncoded();         
	public final static   SymmetricCrypto aes = SecureUtil.aes(byteKey);
	public static final String dataFilePath = getjarpath().concat("\\encodedata\\");
	public static final String dataFilename = dataFilePath.concat("data.data");
	public static final String testFilename = dataFilePath.concat("testFilename.data");
    public static Boolean encode(File file) {
    	
    	try {
  
        if(file!=null){
            if(file.isFile()){
      
		            	
				    //文件绝对路径
				  String fileName = file.getAbsolutePath();
		
		             //  当前文件所在路径
		          String partdir = fileName.substring(0,fileName.lastIndexOf("\\")+1);
		          
		            //  文件名称
		         
		          String oldfileName = fileName.substring(fileName.lastIndexOf("\\")+1);  
		       
		   

		          String encodeName =  URLEncoder.encode( aes.encryptBase64(oldfileName),"utf-8");
		       
				  
			             // 文件新名字
			    File newName= new File(partdir+ encodeName);
			   
	
			   
			    file.renameTo(newName);
		 
        
                
            }else if(file.isDirectory()){
            	
                File[] files = file.listFiles();
                for (File file1 : files) {
                	//递归
                	encode(file1);
                }
            }else{
                return true;
            }
     
        }
    	}catch(Exception e){
    		 JOptionPane.showMessageDialog(null, "获取文件权限异常");
    		System.out.println("encode异常");
    		e.printStackTrace();
    		
    		System.exit(1000);
    	}
        return true;
    }
    public static Boolean decode(File file) {
    

    	try{
    	  
        if(file!=null){
            if(file.isFile()){
      
		            
				    //文件绝对路径
				  String fileName = file.getAbsolutePath();
		
		             //  当前文件所在路径
		          String partdir = fileName.substring(0,fileName.lastIndexOf("\\")+1);
		          
		            //  文件名称
		         
		          String oldfileName = fileName.substring(fileName.lastIndexOf("\\")+1);  
		          

		          String decryptData = aes.decryptStr(URLDecoder.decode(oldfileName,"utf-8"));
		   
			         
			             // 文件新名字
			    File newName= new File(partdir+ decryptData);
			
		             // 重命名
			    file.renameTo(newName);
		        
                
            }else if(file.isDirectory()){
            	
                File[] files = file.listFiles();
                for (File file1 : files) {
                	//递归
                	decode(file1);
                }
            }else{
            
                return true;
            }
           
        }
    	}catch(Exception e){
    		 JOptionPane.showMessageDialog(null, "解密文件包含非加密文件，已跳过");
    		
    		
    	}
    	
        return true;
    }
    
    public static void exeCmd(String commandStr) {
        BufferedReader br = null;
        try {
            Process p = Runtime.getRuntime().exec(commandStr);
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
              
            }
        } catch (Exception e) {
        	JOptionPane.showMessageDialog(null, "获取文件权限异常");
        	  e.printStackTrace();
        	 
        	System.exit(1000);
          
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                	  JOptionPane.showMessageDialog(null, "获取文件权限异常");
                    e.printStackTrace();
                 
                    System.exit(1000);
                }
            }
        }
   }
    
    public static void appenderFileName(File file) {


    	
    	
     	try {

     	File f = new File(dataFilePath);
    	  
    	  if(!f.exists()){
    		  System.out.println("创建文件夹");
    		  f.mkdirs();
    	  }
     		 
    	   f = new File(dataFilename);
    	   
    	  if(!f.exists()){
    		    System.out.println("创建文件");
    		f.createNewFile();
    	  	}
    	  
    	FileAppender appender = new FileAppender(f, 16, true);
    	String appand = null;
		appand = URLEncoder.encode( aes.encryptBase64(file.getAbsolutePath()),"utf-8");		
		appender.append(appand);
		appender.flush();
		appender.toString();
     	}catch (Exception e) {
				// TODO Auto-generated catch block
     		JOptionPane.showMessageDialog(null, "获取文件权限异常");
     		e.printStackTrace();
     	
     		System.exit(1000);
		
		
     	}
    }
    private static Exception RuntimeException(String string) {
		// TODO Auto-generated method stub
		return null;
	}
	public static List<String> getHistoryFileName() {
    	
       	File f = new File(dataFilePath);
  	  System.out.println("加密文件存储路径："+f.getAbsolutePath());
  	  if(!f.exists()){
  		  System.out.println("创建文件夹");
  		  f.mkdirs();
  	  }
   		 
  	   f = new File(dataFilename);
  	   
  	  if(!f.exists()){
  		    System.out.println("创建文件");
  		try {
			f.createNewFile();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "获取文件权限异常");
			e.printStackTrace();
			
			System.exit(1000);
	
			// TODO Auto-generated catch block
			
		}
  	  	}
  	  
    	FileReader fileReader = new FileReader(f);
    	
    	
    	
    	List<String> fileNames = fileReader.readLines();
    	for(int i = 0 ;i <fileNames.size();i++)
    	{
    		
    		try {
				fileNames.set(i, aes.decryptStr(URLDecoder.decode(fileNames.get(i),"utf-8")));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				JOptionPane.showMessageDialog(null, "获取文件权限异常");
				e.printStackTrace();
				 
				System.exit(1000);
			}
    		
    	}
    	
    	return fileNames;
    }
  public static void overwritegetHistoryFileName() {
	   	File f = new File(dataFilePath);
  	  
  	  if(!f.exists()){
  		  System.out.println("创建文件夹");
  		  f.mkdirs();
  	  }
   		 
  	   f = new File(dataFilename);
  	   
  	  if(!f.exists()){
  		    System.out.println("创建文件");
  		try {
			f.createNewFile();
		} catch (IOException e) {
			
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null, "获取文件权限异常");
			e.printStackTrace();
		
			System.exit(1000);
		}
  	  	}
  	  
	 
    	FileWriter writer = new FileWriter(f);
    	writer.write("");
    
    	
    }
  
  
  public static String getjarpath(){
	 
  	String filePath = EncodeUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
  			
  	try {
  		filePath = URLDecoder.decode(filePath,"utf-8");
 
  		filePath = filePath.substring(0,filePath.lastIndexOf("/"));

	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		JOptionPane.showMessageDialog(null, "获取文件权限异常");
		e.printStackTrace();
		
		System.exit(1000);
	}
  	return filePath;
  }
  
  


}
